package com.yougou.ui.category.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.yougou.R;
import com.yougou.data.model.Category;

import java.util.ArrayList;
import java.util.List;

public class SubCategoryAdapter extends RecyclerView.Adapter<SubCategoryAdapter.ViewHolder> {
    
    private List<Category> mDataList = new ArrayList<>();
    private int mSelectedPosition = 0;
    private OnItemClickListener mListener;
    
    public interface OnItemClickListener {
        void onItemClick(Category category, int position);
    }
    
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }
    
    public void setData(List<Category> dataList) {
        if (dataList != null) {
            mDataList = dataList;
            mSelectedPosition = 0;
            notifyDataSetChanged();
        }
    }
    
    public void setSelectedPosition(int position) {
        int oldPosition = mSelectedPosition;
        mSelectedPosition = position;
        notifyItemChanged(oldPosition);
        notifyItemChanged(mSelectedPosition);
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_sub_category, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = mDataList.get(position);
        holder.tvSubCategory.setText(category.getCatName());
        
        // 设置选中状态
        if (position == mSelectedPosition) {
            holder.tvSubCategory.setBackgroundResource(R.drawable.bg_circle);
            holder.tvSubCategory.setTextColor(ContextCompat.getColor(
                    holder.itemView.getContext(), R.color.white));
        } else {
            holder.tvSubCategory.setBackgroundResource(R.drawable.bg_search_input);
            holder.tvSubCategory.setTextColor(ContextCompat.getColor(
                    holder.itemView.getContext(), R.color.color_text_secondary));
        }
        
        // 点击事件
        holder.itemView.setOnClickListener(v -> {
            if (mListener != null) {
                setSelectedPosition(position);
                mListener.onItemClick(category, position);
            }
        });
    }
    
    @Override
    public int getItemCount() {
        return mDataList.size();
    }
    
    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvSubCategory;
        
        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvSubCategory = itemView.findViewById(R.id.tv_sub_category);
        }
    }
}

